package cn.dujc.superkid.fragment;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import cn.dujc.core.adapter.BaseQuickAdapter;
import cn.dujc.core.ui.BaseFragment;
import cn.dujc.core.util.ToastUtil;
import cn.dujc.superkid.R;
import cn.dujc.superkid.activities.LoginActivity;
import cn.dujc.superkid.adapter.ErrorQueAdapter;
import cn.dujc.superkid.adapter.RecyclerViewAdapter;
import cn.dujc.superkid.api.HttpHelper;
import cn.dujc.superkid.api.QMap;
import cn.dujc.superkid.api.Result;
import cn.dujc.superkid.api.ResultCallBack;
import cn.dujc.superkid.bean.RegisterResult;
import cn.dujc.superkid.bean.WrongQuestionResult;
import cn.dujc.superkid.utils.Preferences;

public class ErrorFragment extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener, ErrorQueAdapter.OnItemClickListener, BaseQuickAdapter.OnItemLongClickListener {
    RecyclerView recyclerView;
    private List<String> list = new ArrayList<>();
    private ErrorQueAdapter recyclerViewAdapter;
    private int page;
    String cId;
    BroadcastReceiver receiver;
    String action = "";

    @Override
    public int getViewId() {
        return R.layout.fragment_list;
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        cId = getArguments().getString("category_id");
        action = "refresh_error" + cId;
        init();
        initBroadCast();
        initLogic();
        loadData();
    }

    private void initBroadCast() {
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(action)) {
                    loadData();
                }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(action);
        mActivity.registerReceiver(receiver, intentFilter);
    }

    //    video/good_question
    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(receiver);
    }

    private void delete(final int pos) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("提示").setMessage("确认删除这条记录吗？").setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                RegisterResult loginResult = Preferences.getInstance().getLoginResult(mActivity);
                QMap map = QMap.build()
                        .put("wrong_question_id", recyclerViewAdapter.getData().get(pos).getId())
                        .put("user_id", Integer.parseInt(loginResult.getUid()))
                        .put("channel", Preferences.getInstance().getChannel(mActivity).getChannel_id())
                        .put("logincode", loginResult.getLogincode()).create();
                Log.e("qqmap", map.toString());
                HttpHelper.getUserCenter().memberDelWrongQuestion(map).enqueue(new ResultCallBack<Result<Object>>(mActivity) {
                    @Override
                    public void onSuccessCallback(int code, Result<Object> body) {
                        ToastUtil.showToast(mActivity, body.getMsg());
                        recyclerViewAdapter.remove(pos);
                    }
                });
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ToastUtil.showToast(getContext(), "取消操作");
            }
        });
        builder.show();
    }

    private void initLogic() {
        for (int i = 0; i < 20; i++) {
            list.add("测试");
        }
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this.getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        DividerItemDecoration divider = new DividerItemDecoration(this.getContext(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this.getContext(), R.drawable.decoration));
        recyclerView.addItemDecoration(divider);
        recyclerViewAdapter = new ErrorQueAdapter(R.layout.item_error_que, null);
        recyclerViewAdapter.setOnItemLongClickListener(this);
        recyclerViewAdapter.setOnItemClickListeners(this);
        recyclerViewAdapter.setAction(action);
        recyclerViewAdapter.setOnLoadMoreListener(this, recyclerView);
        recyclerView.setAdapter(recyclerViewAdapter);
    }

    private void init() {
        recyclerView = (RecyclerView) findViewById(R.id.test_recyclerview);
    }

    private void loadData() {
        if (!Preferences.isLogin(this)) {
            starter().go(LoginActivity.class);
        }
        final RegisterResult loginResult = Preferences.getInstance().getLoginResult(mActivity);
        HttpHelper.getUserCenter().memberWrongQuestion(QMap.build()
                .put("category_id", cId)
                .put("user_id", loginResult.getUid())
                .put("channel", Preferences.getInstance().getChannel(mActivity).getChannel_id())
                .put("logincode", loginResult.getLogincode())
                .put("num", "20")
                .put("page", page + "")
                .create()).enqueue(new ResultCallBack<Result<WrongQuestionResult>>(mActivity) {
            @Override
            public void onSuccessCallback(int code, Result<WrongQuestionResult> body) {
                List<WrongQuestionResult.ListBean> datas = body.getData().getList();
                if (page == 0) {
                    recyclerViewAdapter.setNewData(datas);
                } else {
                    recyclerViewAdapter.addData(datas);
                    recyclerViewAdapter.loadMoreComplete();
                }
                if (datas.size() < 20) {
                    recyclerViewAdapter.loadMoreEnd();
                }
            }

            @Override
            public void onFailureCallback(int code, String msg) {
                recyclerViewAdapter.setEmptyView(R.layout.layout_empty);
            }
        });
    }

    @Override
    public void onLoadMoreRequested() {
        page++;
        loadData();
    }

    @Override
    public void onItemClick(WrongQuestionResult.ListBean item) {
        final RegisterResult loginResult = Preferences.getInstance().getLoginResult(mActivity);
        HttpHelper.getCourse().videoGoodQuestion(QMap.build()
                .put("user_id", loginResult.getUid())
                .put("channel", Preferences.getInstance().getChannel(mActivity).getChannel_id())
                .put("exercises_id", item.getId())
                .put("logincode", loginResult.getLogincode())
                .put("type_id", 1)
                .create()).enqueue(new ResultCallBack<Result<Object>>(mActivity) {
            @Override
            public void onSuccessCallback(int code, Result<Object> body) {
                ToastUtil.showToast(mActivity, body.getMsg());
            }

            @Override
            public void onFailureCallback(int code, String msg) {
                if(code==400){
                    ToastUtil.showToast(getActivity(), msg);
                }else{
                    ToastUtil.showToast(getActivity(), "未能读取数据，因为它的格式不正确");
                }
            }
        });
    }

    @Override
    public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
        delete(position);
        return false;
    }
}
